package com.swlz.listenter;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.swlz.commons.ELTools;
import com.swlz.commons.FastJSONConfig;
import com.swlz.service.ConfigService;
import com.swlz.service.impl.ConfigServiceImpl;

@WebListener
public class SystemListener implements HttpSessionListener,ServletContextListener {

	private int count = 0;
	private int online = 0;
	
	private ServletContext application;
	private ConfigService service = new ConfigServiceImpl();
	
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		//读取之前保存的访问数量
		count = service.getCount();
		
		application = sce.getServletContext();
		application.setAttribute("count", count);
		application.setAttribute("online", online);
		
		//添加一个全局给EL表达式使用的工具对象
		application.setAttribute("t", new ELTools());
		
		//添加全局的系统配置
		application.setAttribute("config", service.getSystemConfig());
		
		//全局的FastJSON的配置
		FastJSONConfig.getConfig().initConfig();
	}
	
	
	@Override
	public void sessionCreated(HttpSessionEvent se) {
		count ++;
		online ++;
//		se.getSession().getServletContext().setAttribute("count", count);
//		se.getSession().getServletContext().setAttribute("online", online);
		application.setAttribute("count", count);
		application.setAttribute("online", online);
	}
	
	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		online --;
		application.setAttribute("online", online);
	}
	
	
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		// 保存现在访问的人数
		service.saveCount(count);
	}
}
